/*
Copyright (c) 2011, Jeffrey Kunkel
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions 
are met:

Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.
Neither the name of the Jeffrey Kunkel nor the names of its contributors 
may be used to endorse or promote products derived from this software 
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
*/

/// *************** TEST 1 *******************
#include <MicroThreads.hpp>
#include <iostream>

namespace {
boost::mutex io_lock;
#define sync_io( exe ) { io_lock.lock(); {exe} io_lock.unlock(); }
void hello() {
  sync_io(
    std::cout<<"hello ";
  );
}
void my() {
  sync_io(
    std::cout<<"my ";
  );
}
void dear() {
  sync_io(
    std::cout<<"dear ";
  );
}
void daisy() {
  sync_io(
    std::cout<<"daisy!"<<std::endl;
  );
}

void test1() {
  MicroThreadExecution<> exe( 8 );

  boost::function0<void> functions[4] = { 
    boost::function0<void>(hello), 
    boost::function0<void>(my), 
    boost::function0<void>(dear), 
    boost::function0<void>(daisy) };

  for( int i = 0; i < 800; ++i ) 
    exe.produce( functions[ i&3 ] );

  exe.join();
}
}
/// ******************************************

/// *************** TEST 2 *******************
namespace CLASSES {
  enum {
    my_point = 1, 
    my_transform = 2,
    my_random_class = 3
  };
}
class my_point {
  const int x,y;
public:
  my_point( const int x, const int y ) 
    : x(x), y(y) {}
  virtual ~my_point() {}
  virtual int getx() const { return x; }
  virtual int gety() const { return y; }
};
class my_transform : public my_point {
public:
  my_transform( const int x, const int y ) 
    : my_point(x*x,y*y) {}
  virtual ~my_transform() {}
};
class my_random_class {
public:
  int x,y,z;
  my_random_class() {
    x = rand(); y = rand(); z = rand();
  }
};

void handle_errors( std::pair<int, void*> & point_object ) {
  io_lock.lock();
  my_point * pnt = 0;
  if( CLASSES::my_point == point_object.first ) {
    pnt = static_cast<my_point*>(point_object.second);
    std::cout<<"my_point class (x,y) = " ;
  }
  if( CLASSES::my_transform == point_object.first ) {
    pnt = static_cast<my_transform*>(point_object.second);
    std::cout<<"my_transform class (x,y) = ";
  }
  if( pnt ) {
    std::cout<< "(" <<pnt->getx()<<","<<pnt->getx() << ")" 
      << std::endl;
    io_lock.unlock();
    delete pnt;
    return;
  }

  if( CLASSES::my_random_class == point_object.first ) {
    my_random_class * rnd = static_cast<my_random_class*>(point_object.second);
    std::cout<<"random class (x,y,z) = (" 
      <<rnd->x<<","<<rnd->y<<","<<rnd->z << ")" 
      << std::endl;
    io_lock.unlock();
    delete rnd;
    return;
  }

  std::cout<<"Unknown Message: "<< point_object.first << std::endl;
  io_lock.unlock();
}

void random_failures() {
  int r = abs(rand());
  if( r%10 < 3 ) {
    switch( rand() % 4 ) {
      case 0: break;
      case CLASSES::my_point: {
        my_point * pnt = new my_point( rand() * 10000, rand() * 10000 );
        throw std::pair<int,void*>
          ( CLASSES::my_point, (void*)pnt );
        break;
      }
      case CLASSES::my_transform: {
        my_transform * pnt = new my_transform( rand() * 10000, rand() * 10000 );
        throw std::pair<int,void*>
          ( CLASSES::my_transform, (void*)pnt );
        break;
      }
      case CLASSES::my_random_class: {
        my_random_class * pnt = new my_random_class();
        throw std::pair<int,void*>
          ( CLASSES::my_random_class, (void*)pnt );
        break;
      }
    }
  }
}

void test2() {
  const int thread_count = 16;
  MicroThreadExecution<> exe(thread_count, handle_errors);
  for( int i = 0; i < 1000; ++i ) 
    exe.produce( random_failures );
  exe.join();
  return;
}
/// ******************************************

/// *************** TEST 3 *******************
// This example shows how to share data between 
// running threads. Second, this example shows
// how to stop a thread at predefined points.

struct run_forever {
  struct Static {
    MicroThreadExecution<> * exe;
  } * const st;
  struct Shared {
    boost::thread * thread;
    boost::mutex scheduled_haults;
  } * const  sh;

  const int who;

  run_forever( Static * st, Shared * sh, const int who ) 
    : st(st), sh(sh), who(who) {}

  void init() {
    sh->thread = st->exe->find_thread_if( is_my_thread() );
  }
  void destory() {
    sh->thread = 0;
  }

  void operator()() {
    init();
    while(1) {
      boost::xtime tm;
      tm.nsec = (boost::xtime::xtime_nsec_t)
        boost::posix_time::microseconds(500).total_nanoseconds();
      boost::this_thread::sleep( tm );
      if( false == sh->scheduled_haults.try_lock() ) 
        break;
      sh->scheduled_haults.unlock();

      io_lock.lock();
      std::cout<<"HAHA!, "<<who<<" is still alive!"<<std::endl;
      io_lock.unlock();
    }
    destory();
  }
};

struct stop_the_madness {
  run_forever::Static * const st;
  run_forever::Shared * const sh;
  stop_the_madness( run_forever::Static * st, run_forever::Shared * sh ) 
    : st(st), sh(sh) {}
  void operator()() {
    sh->scheduled_haults.lock();
  }
};

void test3() {
  MicroThreadExecution<> exe( 256 );
  
  run_forever::Static st;
  st.exe = &exe;

  const int elem_size = 64;
  run_forever::Shared sh[elem_size];
  int elem_top = 0;
  int elem_left = 0;


  // Block all threads.
  for( int i = 0; elem_top < elem_size; ++i ) {
    int pr = rand() % 100;
    if( pr < 10 ) {
      exe.produce( run_forever( &st, &sh[elem_top++], elem_top ) );
    } else if( pr < 20 && elem_left < elem_size ) {
      exe.produce( stop_the_madness( &st, &sh[elem_left++] ) );
    } else {
      exe.produce( hello );
      exe.produce( my );
      exe.produce( dear );
      exe.produce( daisy );
    }
  }

  for( int i = elem_left; i < elem_size; ++i ) {
    sh[i].scheduled_haults.lock(); 
  }

  exe.join();
}
/// ******************************************

/// *************** TEST 4 *******************
void test4() {
}
/// ******************************************

int main() {
  test1();
  test2();
  test3();
  test4();
  return 0;
}
